class BooksController < ApplicationController
  before_filter :admin_check, except: [:index, :show, :rate, :comment]
  helper_method :sort_column, :sort_direction

  # GET /books
  def index
    @books = Book.paginate(:page => params[:page], per_page: 20, 
                           order: "#{params[:sort]} #{params[:direction]}")

    respond_to do |format|
      format.html # index.html.erb
    end
  end

  # GET /books/1
  def show
    @book = Book.find(params[:id])
    @comments = @book.comments.recent.limit(10).all

    respond_to do |format|
      format.html # show.html.erb
    end
  end

  # GET /books/new
  def new
    @book = Book.new

    respond_to do |format|
      format.html # new.html.erb
    end
  end

  # GET /books/1/edit
  def edit
    @book = Book.find(params[:id])
  end

  # POST /books
  def create
    @book = Book.new(params[:book])

    respond_to do |format|
      if @book.save
        format.html { redirect_to @book, notice: 'Book was successfully created.' }
      else
        format.html { render action: "new" }
      end
    end
  end

  # PUT /books/1
  def update
    @book = Book.find(params[:id])

    respond_to do |format|
      if @book.update_attributes(params[:book])
        format.html { redirect_to @book, notice: 'Book was successfully updated.' }
      else
        format.html { render action: "edit" }
      end
    end
  end

  # DELETE /books/1
  def destroy
    @book = Book.find(params[:id])
    @book.destroy

    respond_to do |format|
      format.html { redirect_to books_url }
    end
  end

  def rate
    @book = Book.find(params[:id])
    @book.rate(params[:stars], current_user, params[:dimension])
    
    respond_to do |format|
      format.html { redirect_to :back  }
    end
  end

  def comment
    @book = Book.find(params[:id])
    comment = @book.comments.create(title: params[:title], comment: params[:comment])
    comment.user = current_user
    comment.save

    respond_to do |format|
      format.html { redirect_to :back }
    end
  end

  protected

  def admin_check
    unless current_user.admin?
      flash[:notice] = t('errors.messages.no_permission')
      redirect_to books_path 
    end
  end

  def sort_column
    Book.column_names.include?(params[:sort]) ? params[:sort] : "name"
  end

  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end
end
